package com.wpf.rounter2function.handler;


import com.wpf.rounter2function.bean.Person;
import com.wpf.rounter2function.dao.PersonDao;
import com.wpf.rounter2function.utils.ValidUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

@Log4j2
@Component
public class PersonHandler {

    private final PersonDao personDao;

    public PersonHandler(PersonDao personDao){
        this.personDao = personDao;
    }


    public Mono<ServerResponse> queryAll(ServerRequest request){
        log.info("~~~~~~queryAll~~~~~~");
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(this.personDao.findAll(), Person.class);
    }

    public Mono<ServerResponse> save(ServerRequest request){
        /*log.info("~~~~~~save~~~~~~");
        Mono<Person> person = request.bodyToMono(Person.class);
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(this.personDao.saveAll(person),Person.class);*/

        // 这儿的代码是加了参数检验
        Mono<Person> person = request.bodyToMono(Person.class);
        return person.flatMap(p->{
            log.info("参数校验开始...");
            ValidUtil.validVale(p);
            log.info("参数校验结束...");
            return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                    .body(this.personDao.save(p),Person.class);
        });


    }


    public Mono<ServerResponse> delete(ServerRequest request){
        log.info("~~~~~~delete~~~~~~");
        String id = request.pathVariable("id");
        return this.personDao.findById(id)
                .flatMap(person -> this.personDao.delete(person).then(ServerResponse.ok().build()))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

}
